package org.example.controller;
import org.example.pojo.Door;
import org.example.pojo.Order;
import org.example.service.DoorService;
import org.example.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private DoorService doorService;

    @RequestMapping(value = "/orderList",method = RequestMethod.GET)
    public String getAllOrder(Model model) {
        List<Order> list = orderService.getAllOrder();
        List<Door> doorList = doorService.getAllDoor();
        model.addAttribute("doorList", doorList);
        model.addAttribute("list", list);
        return "order_list";
    }

    @RequestMapping(value = "/findAllDoorToOrderAdd")
    public String door_add(Model model) {
        List<Door> list = doorService.getAllDoor();
        model.addAttribute("doorList", list);
        return "order_add";
    }

    @RequestMapping(value = "/orderAdd",method = RequestMethod.POST)
    public String addOrder(Order order) {
        Date currentDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = dateFormat.format(currentDate);
        order.setOrderTime(formattedDate);
        order.setPayTime(formattedDate);
        orderService.addOrder(order);
        return "redirect:/orderList";
    }

    @RequestMapping(value = "/orderInfo/orderUpdate",method = RequestMethod.POST)
    public String updateOrder( Order order) {
        orderService.update(order);
        return "redirect:/orderList";
    }

    @RequestMapping(value = "/orderInfo/{id}",method = RequestMethod.GET)
    public String getDoor(Model model, @PathVariable("id") Integer id) {
        Order order= orderService.getOrder(id);
        List<Door> doorList = doorService.getAllDoor();
        model.addAttribute("doorList", doorList);
        model.addAttribute("order",order);
        return "order_update";
    }

    @RequestMapping(value = "/orderDelete/{id}",method = RequestMethod.GET)
    public String deleteOrder( @PathVariable("id") Integer id) {
        orderService.deleteOrder(id);
        return "redirect:/orderList";
    }


}
